import { fetchAllMedifoodDetails } from '../../Service/CategoryService';

Page({
  data: {
    medicatedFoods: [], // 药膳信息按首字母分组
    alphabet: [
      { letter: 'A' },
      { letter: 'B' },
      { letter: 'C' },
      { letter: 'D' },
      { letter: 'E' },
      { letter: 'F' },
      { letter: 'G' },
      { letter: 'H' },
      { letter: 'I' },
      { letter: 'J' },
      { letter: 'K' },
      { letter: 'L' },
      { letter: 'M' },
      { letter: 'N' },
      { letter: 'O' },
      { letter: 'P' },
      { letter: 'Q' },
      { letter: 'R' },
      { letter: 'S' },
      { letter: 'T' },
      { letter: 'U' },
      { letter: 'V' },
      { letter: 'W' },
      { letter: 'X' },
      { letter: 'Y' },
      { letter: 'Z' },
      { letter: '#' } // 增加 '#' 选项
    ],
    toView: '', // 滚动到的目标元素id
    activeLetter: '', // 当前激活的字母
    letterPositions: {} // 每个字母组的位置
  },

  onLoad() {
    this.loadMedifoodDetails();
  },

  onShow() {
    this.loadMedifoodDetails();
  },

  async loadMedifoodDetails() {
    try {
      const medifoodDetails = await fetchAllMedifoodDetails();
      const groupedData = this.groupByInitialLetter(medifoodDetails);
      this.setData({ medicatedFoods: groupedData }, () => {
        this.calculateLetterPositions(); // 计算字母组的位置
      });
    } catch (error) {
      console.error('加载药膳信息失败:', error);
    }
  },

  groupByInitialLetter(medifoodDetails) {
    const grouped = {};
    medifoodDetails.forEach(item => {
      let letter = item.initial_letter ? item.initial_letter.toUpperCase() : '';
      if (!/^[A-Z]$/i.test(letter)) {
        letter = '#';
      }
      if (!grouped[letter]) {
        grouped[letter] = [];
      }
      grouped[letter].push(item);
    });
    return Object.entries(grouped).map(([letter, items]) => ({
      letter,
      items
    }));
  },

  calculateLetterPositions() {
    const letterPositions = {};
    const query = wx.createSelectorQuery();
    this.data.alphabet.forEach(item => {
      query.select(`#${item.letter}`).boundingClientRect(rect => {
        if (rect) {
          letterPositions[item.letter] = rect.top;
        }
      });
    });
    query.exec(() => {
      this.setData({ letterPositions });
    });
  },

  getAlphabetId: function (e) {
    const clickedLetter = e.currentTarget.dataset.letter;
    const medicatedFoodGroup = this.data.medicatedFoods.find(group => group.letter === clickedLetter);
    if (medicatedFoodGroup && medicatedFoodGroup.items.length > 0) {
      this.setData({
        toView: clickedLetter,
        activeLetter: clickedLetter
      });
    } else {
      wx.showModal({
        title: '抱歉',
        content: '当前字母组中没有药膳',
        showCancel: false,
        confirmText: '确定',
        confirmColor: '#17cc84'
      });
    }
  },

  handleClick(event) {
    const id = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/Not-tabbar/HC_info/HC_info?id=${id}`
    });
  },

  onScroll(event) {
    const scrollTop = event.detail.scrollTop;
    let activeLetter = '';
    for (const [letter, position] of Object.entries(this.data.letterPositions)) {
      if (scrollTop >= position-10) {
        activeLetter = letter;
      } else {
        break;
      }
    }
    this.setData({ activeLetter });
  }
});
